package cn.fulong.sso.client.manager.impl;


import cn.fulong.sso.client.manager.AbstractSessionManager;
import cn.fulong.sso.client.utils.CollectionUtils;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpSession;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @desc: 单机环境下SessionManger实现
 * @author: 云树
 * @createDate: 2019/1/17 10:24
 * @version: 1.0
 */
@Slf4j
public class ConcurrentHashMapPlusSessionManager extends AbstractSessionManager {


    /**
     * token 映射 sessionId 会话存储
     */
    private final ConcurrentHashMap<String, Set<HttpSession>> tokenMappingSession = new ConcurrentHashMap();

    @Override
    public boolean removeSessionManagerByToken(String token) {
        Set<HttpSession> sessions = tokenMappingSession.get(token);
        if (!CollectionUtils.isEmpty(sessions)) {
            for (HttpSession session : sessions) {
                try {
                    session.invalidate();
                } catch (Exception e) {
                    log.error("【ConcurrentHashMapSessionManager】根据sessionId清除会话", e);
                }
            }
        }
        this.removeTokenMappingSessionByToken(token);
        return true;
    }

    @Override
    public boolean addTokenSessionStorage(String token, HttpSession sessionStorage) {
        Set<HttpSession> sessions = tokenMappingSession.get(token);
        if (null == sessions) {
            sessions = new HashSet<>(4);
            sessions.add(sessionStorage);
            tokenMappingSession.put(token, sessions);
        } else {
            sessions.add(sessionStorage);
        }
        log.debug("【ConcurrentHashMapPlusSessionManager】映射会话 token= {},sessionId= {}", token, sessionStorage);
        return true;
    }

    @Override
    public boolean removeTokenMappingSessionByToken(String token) {
        Set<HttpSession> sessions = tokenMappingSession.get(token);
        if (token != null) {
            tokenMappingSession.remove(token);
        }
        if (!CollectionUtils.isEmpty(sessions)) {
            sessions.clear();
        }
        return true;
    }


}
